/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import DictTag from "@/components/DictTag";
import { CloudDownloadOutlined, DeleteOutlined, ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import { Button, Divider, FormInstance, Input, Modal, Popconfirm, Space, Typography, message } from "antd";
import { DataNode } from "antd/es/tree";
import React, { useEffect, useRef, useState } from "react";
import DataScope from "./components/DataScope";
import MenuForm from "./components/MenuForm";
import RoleForm, { RoleFormData } from "./components/RoleForm";
// import DataScopeForm from './components/DataScope';
// import UpdateForm from './edit';
import CustomerTable from "@/components/CustomerTable";
import { getPageList, remove, save, update } from "@/services/api/module/system/role";
import { getDict } from "@/services/api/module/system/dict";
import FilterDrawer from "@/components/FilterDrawer";
import ImportExportDropdown from "@/components/ImportExportDropdown";
import { createTableColumns, pagination } from "./contents";

const { confirm } = Modal;
const RoleTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const [menuOpen, setMenuOpen] = useState<boolean>(false);
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const [menuVisible, setMenuVisible] = useState<boolean>(false);
	const [dataScopeModalOpen, setDataScopeModalOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRow, setCurrentRow] = useState<API.Setting.Role>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [scopeRoleId, setScopeRoleId] = useState<number | undefined>(undefined);
	const [scopeOpen, setScopeOpen] = useState<boolean>(false);
	const [selectedRows, setSelectedRows] = useState<API.Setting.Role[]>([]);
	const [menuTree, setMenuTree] = useState<DataNode[]>();
	const [menuIds, setMenuIds] = useState<string[]>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [dataScopeEnums, setDataSCopeEnums] = useState<any>([]);
	const [authMenuOpen, setAuthMenuOpen] = useState<boolean>(false);
	useEffect(() => {
		getDict("sys_base_status").then(data => {
			setStatusOptions(data);
		});
		getDict("sys_data_scope").then(data => {
			setDataSCopeEnums(data);
		});
	}, []);
	const handleColumnEditor = (record: any) => {
		setFormOpen(true);
		setCurrentId(record.id);
	};
	const handleColumnRemove = (record: any) => {
		handleRemove(record?.id);
	};
	const handleColumnAuth = (record: any) => {
		setModalVisible(true);
		setCurrentId(record.id);
	};
	const handleColumnMenu = (record: any) => {
		setAuthMenuOpen(true);
		setCurrentId(record.id);
	};
	const handlePremission = (record: any) => {
		setScopeRoleId(record.id);
		setScopeOpen(true);
	};
	// 列定义
	// 列表字段
	const columns: ProColumns<API.Setting.RoleVo>[] = createTableColumns(
		statusOptions,
		handleColumnEditor,
		handleColumnRemove,
		handleColumnAuth,
		handleColumnMenu,
		handlePremission
	);

	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除角色名称为：${names} 的角色吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};
	// 保存
	const handleSave = async (values: RoleFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as RoleFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 編輯
	const handleUpdate = async (values: RoleFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as RoleFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	const handleFormCancel = () => {
		setFormOpen(false);
		setCurrentId(undefined);
	};
	return (
		<>
			<CustomerTable<API.Setting.RoleVo>
				actionRef={actionRef}
				formRef={formTableRef}
				tableStyle={{ minHeight: "calc(100vh - 200px)" }}
				rowKey="id"
				key="roleList"
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="通过用户账号搜索" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					)
				}}
				search={false}
				pagination={pagination}
				request={tableDataRequest}
				// @ts-ignore
				toolBarRender={() => {
					return (
						<>
							<Button
								type="primary"
								key="add"
								onClick={async () => {
									setFormOpen(true);
								}}
							>
								<PlusOutlined /> 创建角色
							</Button>
							<ImportExportDropdown columns={columns} onExport={function (values: any): Promise<any> {}} />
							{selectedRows.length > 0 && (
								<Button
									type="primary"
									key="remove"
									danger
									hidden={selectedRows?.length === 0}
									onClick={async () => {
										//todo 如果选中包含超级管理员也没办法显示，需要做
										showRemoveConfirm(
											Array.from(selectedRows, ({ id }) => id),
											Array.from(selectedRows, ({ roleName }) => roleName)
										);
									}}
								>
									<DeleteOutlined />
									批量删除
								</Button>
							)}
						</>
					);
				}}
				tableAlertRender={false}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
			/>
			<RoleForm
				onSubmit={async (values: RoleFormData) => {
					return values.id ? await handleUpdate(values) : await handleSave(values);
				}}
				onCancel={handleFormCancel}
				id={currentId}
				open={formOpen}
				statusOptions={statusOptions}
			/>
			<MenuForm
				onSubmit={async (values: API.Setting.Role) => {}}
				open={authMenuOpen}
				onCancel={() => {
					setCurrentId(undefined);
					setAuthMenuOpen(false);
				}}
				idValue={currentId}
				deptCheckedKeys={[]}
			/>
		</>
	);
};

export default RoleTableList;
